﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Threading;

namespace NetFlux
{
    public class ConnectionForwarder
    {
        int port;
        string destinationHost;
        int destinationPort;

        public ConnectionForwarder(string destination, int destinationPort, int localPort)
        {
            this.port = localPort;

            this.destinationHost = destination;
            this.destinationPort = destinationPort;
        }

        static void WriteOut(string text, NetworkStream stream)
        {
            byte[] data = Encoding.ASCII.GetBytes(text);
            stream.Write(data, 0, data.Length);
        }

        TcpListener server;
        Thread listenThread;
        public void Start()
        {
            try
            {
                
                server = new TcpListener(IPAddress.Any,port);
                server.Start();
            }
            catch
            {
                throw new Exception("Could not open port");
            }

            listenThread = new Thread(() =>
            {
                while (true)
                {
                    TcpClient client = server.AcceptTcpClient();

                    new Thread(() =>
                    {
                        try
                        {
                            TcpClient destination = new TcpClient(destinationHost, destinationPort);

                            NetworkStream destinationStream = destination.GetStream();
                            NetworkStream clientStream = client.GetStream();
                            Pwned.Connection connection = new Pwned.Connection(clientStream, destinationStream);
                            connection.Run();
                            //Clean up
                            destination.Close();
                            client.Close();
                            connection = null;
                            destinationStream = null;
                            clientStream = null;

                        }
                        catch
                        {
                        }
                    }) { IsBackground = true }.Start();
                }

            }) { IsBackground = true };
            listenThread.Start();
        }

        public void Stop()
        {
            try
            {
                server.Stop();
            }
            catch
            {
            }
            try
            {
                listenThread.Abort();
            }
            catch
            {
            }
        }

    }
}
